package org.luxor.commons.security.component;

import org.luxor.commons.core.utils.HttpContextUtils;
import org.luxor.commons.core.utils.StrKit;
import org.luxor.commons.core.web.RestStatus;
import org.luxor.commons.core.web.data.R;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.util.MimeTypeUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author lengleng
 * @date 2019/2/1 客户端异常处理 1. 可以根据 AuthenticationException 不同细化异常处理
 */
public class ResourceAuthExceptionEntryPoint implements AuthenticationEntryPoint {

    public ResourceAuthExceptionEntryPoint() {
    }

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException e) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setCharacterEncoding(StrKit.CHARSET_NAME);
        response.setContentType(MimeTypeUtils.APPLICATION_JSON_VALUE);

        R result = new R<>(RestStatus.UNAUTHORIZED, e.getMessage());
        HttpContextUtils.sendJson(response, result);
    }

}
